﻿using SD.Infrastructure.Repository.EntityFrameworkCore;
using SD.Infrastructure.RepositoryBase;
using SlamDunk.MES.Domain.Entities.ResourceContext;
using SlamDunk.MES.Domain.Entities.StockContext;
using SlamDunk.MES.Domain.IRepositories.Interfaces.StockContext;
using SlamDunk.MES.ReportView.Models;
using SlamDunk.ValueObjects.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace SlamDunk.MES.Repository.Implements.StockContext
{
    /// <summary>
    /// 库存结转记录仓储实现
    /// </summary>
    public class StockSettlementRepository : EFAggRootRepositoryProvider<StockSettlement>, IStockSettlementRepository
    {
        #region # 分页获取库存结转记录列表 —— ICollection<StockSettlement> FindByPage(Guid? materialId...
        /// <summary>
        /// 分页获取库存结转记录列表
        /// </summary>
        /// <param name="materialId">物料定义Id</param>
        /// <param name="materialLotId">物料批次Id</param>
        /// <param name="storageLocationType">储存位置类型</param>
        /// <param name="storageLocationId">储存位置Id</param>
        /// <param name="startSettledDate">结转日期开始</param>
        /// <param name="endSettledDate">结转日期结束</param>
        /// <param name="facilityIds">工厂模型Id集</param>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">页容量</param>
        /// <param name="rowCount">总记录数</param>
        /// <param name="pageCount">总页数</param>
        /// <returns>库存结转记录列表</returns>
        public ICollection<StockSettlement> FindByPage(Guid? materialId, Guid? materialLotId, StorageLocationType? storageLocationType, string storageLocationId, DateTime? startSettledDate, DateTime? endSettledDate, IList<Guid> facilityIds, int pageIndex, int pageSize, out int rowCount, out int pageCount)
        {
            Expression<Func<StockSettlement, bool>> condition =
                x =>
                    (materialId == null || x.MaterialId == materialId) &&
                    (materialLotId == null || x.MaterialLotId == materialLotId) &&
                    (storageLocationType == null || x.StorageLocationType == storageLocationType) &&
                    (string.IsNullOrEmpty(storageLocationId) || x.StorageLocationId == storageLocationId) &&
                    (startSettledDate == null || x.SettledDate >= startSettledDate) &&
                    (endSettledDate == null || x.SettledDate <= endSettledDate);

            IQueryable<StockSettlement> stockSettlements = base.Find(condition);
            if (facilityIds != null && facilityIds.Any())
            {
                stockSettlements = stockSettlements.Where(x => x.FacilityId.HasValue && facilityIds.Contains(x.FacilityId.Value));
            }

            IOrderedQueryable<StockSettlement> orderedResult = stockSettlements.OrderByDescending(x => x.AddedTime);
            IQueryable<StockSettlement> pagedResult = orderedResult.ToPage(pageIndex, pageSize, out rowCount, out pageCount);

            return pagedResult.ToList();
        }
        #endregion

        #region # 分页获取物料库存列表 —— ICollection<MaterialStockInfo> GetMaterialStocksByPage(string keywords...
        /// <summary>
        /// 分页获取物料库存列表
        /// </summary>
        /// <param name="keywords">关键字</param>
        /// <param name="materialId">物料定义Id</param>
        /// <param name="materialLotId">物料批次Id</param>
        /// <param name="supplierId">供应商Id</param>
        /// <param name="storageLocationType">储存位置类型</param>
        /// <param name="storageLocationId">储存位置Id</param>
        /// <param name="facilityIds">工厂模型Id集</param>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">页容量</param>
        /// <param name="rowCount">总记录数</param>
        /// <param name="pageCount">总页数</param>
        /// <returns>物料库存列表</returns>
        public ICollection<MaterialStockInfo> GetMaterialStocksByPage(string keywords, Guid? materialId, Guid? materialLotId, Guid? supplierId, StorageLocationType? storageLocationType, string storageLocationId, IList<Guid> facilityIds, int pageIndex, int pageSize, out int rowCount, out int pageCount)
        {
            IQueryable<StockSettlement> stockSettlements = base.FindAllInner();
            if (facilityIds != null && facilityIds.Any())
            {
                stockSettlements = stockSettlements.Where(x => x.FacilityId.HasValue && facilityIds.Contains(x.FacilityId.Value));
            }

            var stockSettlementGroups = stockSettlements.GroupBy(x => new
            {
                x.MaterialId,
                x.MaterialLotId,
                x.StorageLocationType,
                x.StorageLocationId,
                x.StorageLocationName
            });

            IQueryable<BoundRecord> boundRecords = this._dbContext.Set<BoundRecord>();
            IQueryable<Material> materials = this._dbContext.Set<Material>();
            IQueryable<MaterialLot> materialLots = this._dbContext.Set<MaterialLot>();
            IQueryable<StockSettlement> currentStockSettlements = stockSettlementGroups.Select(x => x
                .OrderByDescending(y => y.SettledDate)
                .ThenByDescending(y => y.AddedTime)
                .FirstOrDefault());

            IQueryable<MaterialStockInfo> materialStocks =
                from stockSettlement in currentStockSettlements
                let settledDate = stockSettlement.SettledDate
                let totalInputRecords = boundRecords.Where(x =>
                    x.MaterialId == stockSettlement.MaterialId &&
                    x.MaterialLotId == stockSettlement.MaterialLotId &&
                    x.StorageLocationType == stockSettlement.StorageLocationType &&
                    x.StorageLocationId == stockSettlement.StorageLocationId &&
                    x.AddedTime >= settledDate &&
                    x.DirectionType == StockDirectionType.Input)
                let totalOutputRecords = boundRecords.Where(x =>
                    x.MaterialId == stockSettlement.MaterialId &&
                    x.MaterialLotId == stockSettlement.MaterialLotId &&
                    x.StorageLocationType == stockSettlement.StorageLocationType &&
                    x.StorageLocationId == stockSettlement.StorageLocationId &&
                    x.AddedTime >= settledDate &&
                    x.DirectionType == StockDirectionType.Output)
                let settledQuantity = stockSettlement.Quantity
                let totalInputQuantity = totalInputRecords.Any() ? totalInputRecords.Sum(x => x.Quantity) : 0
                let totalOutputQuantity = totalOutputRecords.Any() ? totalOutputRecords.Sum(x => x.Quantity) : 0
                let stockQuantity = totalInputQuantity - totalOutputQuantity + settledQuantity
                let material = materials.FirstOrDefault(x => x.Id == stockSettlement.MaterialId)
                let materialLot = stockSettlement.MaterialLotId.HasValue
                    ? materialLots.FirstOrDefault(x => x.Id == stockSettlement.MaterialLotId.Value)
                    : null
                select new MaterialStockInfo
                {
                    MaterialId = material.Id,
                    MaterialNo = material.Number,
                    MaterialName = material.Name,
                    MaterialLotId = materialLot == null ? (Guid?)null : materialLot.Id,
                    SupplierId = materialLot == null ? (Guid?)null : materialLot.SupplierId,
                    SupplierNo = materialLot == null ? null : materialLot.SupplierNo,
                    SupplierName = materialLot == null ? null : materialLot.SupplierName,
                    ProductionBatchNo = materialLot == null ? null : materialLot.ProductionBatchNo,
                    ProducedDate = materialLot == null ? (DateTime?)null : materialLot.ProducedDate,
                    GuaranteePeriodTicks = materialLot == null ? (long?)null : materialLot.GuaranteePeriodTicks,
                    ExpiredDate = materialLot == null ? (DateTime?)null : materialLot.ExpiredDate,
                    ReceptionDate = materialLot == null ? (DateTime?)null : materialLot.ReceptionDate,
                    Specification = materialLot == null ? null : materialLot.Specification,
                    MaterialSourceType = materialLot == null ? (MaterialSourceType?)null : materialLot.MaterialSourceType,
                    StorageLocationType = stockSettlement.StorageLocationType,
                    StorageLocationId = stockSettlement.StorageLocationId,
                    StorageLocationName = stockSettlement.StorageLocationName,
                    TotalInQuantity = totalInputQuantity,
                    TotalOutQuantity = totalOutputQuantity,
                    StockQuantity = stockQuantity,
                    QuantityUnitNo = material.StandardUnitNo
                };

            Expression<Func<MaterialStockInfo, bool>> condition =
                x =>
                    (string.IsNullOrEmpty(keywords) || x.MaterialNo.Contains(keywords) || x.MaterialName.Contains(keywords) || x.SupplierNo.Contains(keywords) || x.SupplierName.Contains(keywords) || x.ProductionBatchNo.Contains(keywords)) &&
                    (materialId == null || x.MaterialId == materialId) &&
                    (materialLotId == null || x.MaterialLotId == materialLotId) &&
                    (storageLocationType == null || x.StorageLocationType == storageLocationType) &&
                    (string.IsNullOrEmpty(storageLocationId) || x.StorageLocationId == storageLocationId);

            materialStocks = materialStocks.Where(condition);
            IOrderedQueryable<MaterialStockInfo> orderedResult = materialStocks.OrderBy(x => x.MaterialNo);
            rowCount = orderedResult.Count();
            pageCount = (int)Math.Ceiling(rowCount * 1.0 / pageSize);
            IQueryable<MaterialStockInfo> pagedResult = orderedResult.Skip((pageIndex - 1) * pageSize).Take(pageSize);

            return pagedResult.ToList();
        }
        #endregion

        #region # 是否存在库存结转记录 —— bool Exists(Guid materialId, Guid? materialLotId...
        /// <summary>
        /// 是否存在库存结转记录
        /// </summary>
        /// <param name="materialId">物料定义Id</param>
        /// <param name="materialLotId">物料批次Id</param>
        /// <param name="storageLocationType">储存位置类型</param>
        /// <param name="storageLocationId">储存位置Id</param>
        /// <returns>是否存在</returns>
        public bool Exists(Guid materialId, Guid? materialLotId, StorageLocationType storageLocationType, string storageLocationId)
        {
            Expression<Func<StockSettlement, bool>> condition =
                x =>
                    (x.MaterialId == materialId) &&
                    (x.MaterialLotId == materialLotId) &&
                    (x.StorageLocationType == storageLocationType) &&
                    (x.StorageLocationId == storageLocationId);

            return base.Exists(condition);
        }
        #endregion
    }
}
